package com.ruoyi.web.controller.member;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.BbgAdvice;
import com.ruoyi.system.domain.BbgMember;
import com.ruoyi.system.service.IBbgAdviceService;
import com.ruoyi.system.service.IBbgMemberService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {


    /**
     * 获取用户openId
     * @param request
     * @return
     */
    private String getOpenId(HttpServletRequest request){
        String openId = null;
        openId = request.getHeader("token");
        return openId;
    }

    @Autowired
    private IBbgMemberService memberService;

    @Autowired
    private IBbgAdviceService adviceService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private QiniuAdapter qiniuAdapter;

    //private static String appId = "wx876fa3312e43b02f";
    //private static String appSecret = "dc9c83eb8cd145e2268721273406c554";

    private static String appId = "wxb2488557c7a8e1c1";
    private static String appSecret = "3a4ff94336227fd2072b1f856db995b9";

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取上传的资料
     * @return
     */
    /**
     * 获取七牛云文件上传Token
     */
    @RequestMapping(value = "/getUploadToken",method = {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT})
    public AjaxResult getUploadToken() {
        try {
            return AjaxResult.success(qiniuAdapter.getUploadToken());
        } catch (Exception e) {
           return AjaxResult.error("获取失败");
        }
    }

    /**
     * 微信公众号登陆
     * @param code
     * @return
     */
    @GetMapping("/login")
    public AjaxResult login(String code){
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
        String rst = HttpUtils.sendGet(tokenUrl);
        /**
         {
         "access_token":"ACCESS_TOKEN",
         "expires_in":7200,
         "refresh_token":"REFRESH_TOKEN",
         "openid":"OPENID",
         "scope":"SCOPE",
         "is_snapshotuser": 1,
         "unionid": "UNIONID"
         }
         */
        if (StringUtils.isNotEmpty(rst)){
            JSONObject json = JSONObject.parseObject(rst);
            if (json.containsKey("access_token")){
                String access_token = json.getString("access_token");
                String openId = json.getString("openid");

                BbgMember m = memberService.selectBbgMemberByOpenId(openId);
                if (m != null){
                    return AjaxResult.success(openId);
                }
                String unionid = json.getString("unionid");
                String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
                rst = HttpUtils.sendGet(userUrl);
                if (StringUtils.isNotEmpty(rst)){
                    json = JSONObject.parseObject(rst);
                    if (json.containsKey("nickname")){
                        String nickName = json.getString("nickname");
                        String headimgurl = json.getString("headimgurl");
                        BbgMember member = new BbgMember();
                        member.setMemberName(nickName);
                        member.setMemberImage(headimgurl);
                        member.setMemberOpenId(openId);
                        member.setMemberUnionId(unionid);
                        memberService.insertBbgMember(member);
                        return AjaxResult.success(openId);
                    }
                }
            }
        }
        return AjaxResult.success("用户登陆出错，请重新登陆");
    }


    /**
     * 门店列表
     * @return
     */
    @GetMapping("/deptList")
    public AjaxResult deptList(HttpServletRequest request){
        SysDept dept = new SysDept();
        dept.setParentId(100L);
        return AjaxResult.success(deptService.selectDeptList(dept));
    }

    /**
     * 获取个人信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(HttpServletRequest request)
    {
        try
        {
            String openId = getOpenId(request);
            if (StringUtils.isEmpty(openId)){
                return AjaxResult.error("缺失token");
            }
            BbgMember member = memberService.selectBbgMemberByOpenId(openId);
            if (member != null){
                return AjaxResult.success(member);
            }
            return AjaxResult.error("没有找到会员信息");
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 建议列表
     * @param request
     * @param advice
     * @return
     */
    @GetMapping("/adviceList")
    public AjaxResult adviceList(HttpServletRequest request, BbgAdvice advice){
        startPage();
        advice.setStatus("2");
        advice.setIsShow("1");
        return AjaxResult.success(adviceService.selectBbgAdviceList(advice));
    }

    /**
     * 我的意见列表
     * @param request
     * @param advice
     * @return
     */
    @GetMapping("/myAdviceList")
    public AjaxResult myAdviceList(HttpServletRequest request, BbgAdvice advice){
        String openId = getOpenId(request);
        if (StringUtils.isEmpty(openId)){
            return AjaxResult.error("请先登陆再查询");
        }
        BbgMember member = memberService.selectBbgMemberByOpenId(openId);
        if (member != null){
            startPage();
            advice.setMemberId(member.getMemberId());
            return AjaxResult.success(adviceService.selectBbgAdviceList(advice));
        }
        return AjaxResult.error("没有找到会员信息");
    }

    /**
     * 提交意见
     * @param request
     * @param advice
     * @return
     */
    @PostMapping("/advice")
    public AjaxResult advice(HttpServletRequest request, @RequestBody BbgAdvice advice){
        String openId = getOpenId(request);
        if (StringUtils.isEmpty(openId)){
            return AjaxResult.error("请先授权登陆再提交意见。");
        }
        if (StringUtils.isEmpty(advice.getContact())){
            return AjaxResult.error("请填写联系方式");
        }
        if (StringUtils.isEmpty(advice.getAdviceMsg())){
            return AjaxResult.error("请填写意见内容");
        }
        if (advice.getDeptId() == null){
            return AjaxResult.error("请选择门店");
        }
        String key = "bbg_advice+"+openId;
        if (redisCache.getCacheObject(key) != null){
            return AjaxResult.error("请勿重复提交！");
        }
        redisCache.setCacheObject(key,advice,3, TimeUnit.SECONDS);
        SysDept dept = deptService.selectDeptById(advice.getDeptId().longValue());
        if (dept == null){
            return AjaxResult.error("没有找到门店信息");
        }
        BbgMember member = memberService.selectBbgMemberByOpenId(openId);
        if (member != null){
            advice.setMemberName(member.getMemberName());
            advice.setMemberId(member.getMemberId());
            advice.setCreateTime(new Date());
            advice.setDeptName(dept.getDeptName());
            advice.setStatus("1");
            advice.setIsShow("1");
            advice.setOrigin("微信公众号");
            if (adviceService.insertBbgAdvice(advice)>0) {
                return AjaxResult.success("反馈意见成功！");
            }
            return AjaxResult.error("反馈意见失败，请稍后再试！");
        }
        return AjaxResult.success("请先授权登陆再提交意见。");
    }

}
